package com.small.site.security;

import com.alibaba.fastjson.JSON;
import com.small.site.constant.Constant;
import com.small.site.enums.ResponseCode;
import com.small.site.exception.Assert;
import com.small.site.pojo.SysPermission;
import com.small.site.util.JwtTokenUtil;
import com.small.site.util.RedisUtil;
import com.small.site.vo.UserDetailsVo;
import lombok.Setter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author xiaochi
 * @date 2021/12/13 17:35
 * @desc 权限认证过滤器
 */
@SuppressWarnings("all")
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {

    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Setter
    private String[] openUrl;
    @Setter
    private UserLoginFilter userLoginFilter;
    @Setter
    private LoginUserDetailsService loginUserDetailsService;

    /**
     * 验证
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getServletPath();
        try {
            if (Arrays.stream(openUrl).noneMatch(x -> antPathMatcher.match(x,url))){
                // 不是开放路径就验证
                this.checkToken(request);
            }
        }catch (AuthenticationException ex){
            // 错误处理器
            logger.error("权限认证异常AuthenticationException：{}",ex);
            userLoginFilter.unsuccessfulAuthentication(request,response,ex);
            return;
        }catch (Exception ex){
            logger.error("权限认证异常Exception：{}",ex);
            userLoginFilter.unsuccessfulException(response,ex);
            return;
        }
        filterChain.doFilter(request,response);
    }

    /**
     * 验证token及设置权限数据
     * @param request
     */
    private void checkToken(HttpServletRequest request) {
        String token = request.getHeader(Constant.User.ACCESS_TOKEN);
        Assert.assertNotNull(token, ResponseCode.TOKEN_NOT_NULL.getMessage());
        String username = JwtTokenUtil.getSubject(token);// 获取用户名
        Assert.assertNotNull(username,new SecurityException(ResponseCode.TOKEN_NO_AVAIL.getMessage()));
        String userTokenKey = Constant.User.USER_TOKEN_KEY + username;
        String userKey = loginUserDetailsService.getEntryCacheKey(username);
        String permissionCacheKey = loginUserDetailsService.getPermissionCacheKey(username);
        Assert.isTure(RedisUtil.hasKey(userKey) && RedisUtil.hasKey(permissionCacheKey) && RedisUtil.hasKey(userTokenKey),new SecurityException(ResponseCode.SYSTEM_USERNAME_OFFLINE.getMessage()));
        Assert.isTure(!(StringUtils.isEmpty(token) || StringUtils.isEmpty(username) || !Objects.equals(token,RedisUtil.get(userTokenKey)) || !JwtTokenUtil.validate(token)),new SecurityException(ResponseCode.TOKEN_NO_AVAIL.getMessage()));
        UserDetails userDetails = null;
        try {
            userDetails = loginUserDetailsService.getUserDetails(JSON.parseObject(RedisUtil.get(userKey), UserDetailsVo.class),JSON.parseArray(RedisUtil.get(permissionCacheKey), SysPermission.class));
        }catch (Exception ex){
            logger.error("缓存获取用户信息失败，{}",ex);
        }finally {
            Assert.assertNotNull(userDetails,new SecurityException(ResponseCode.TOKEN_ERROR.getMessage()));
        }
        // 把验证通过的 token 交给 security
        JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
        jwtAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        // 设置为已登录
        SecurityContextHolder.getContext().setAuthentication(jwtAuthenticationToken);
    }
}
